/**
 * Filename: SharePhotoActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/6/19 2:57
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.SharePhotoAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择图片分享页面
 */
public class SharePhotoActivity extends BaseActivity implements ISkinUpdate {
    private Toolbar mToolbar;
    private GridView gv_share_photo;
    private SharePhotoAdapter mAdapter;
    private List<String> mPhotoDatas = new ArrayList<>();
    private Handler handler = new Handler();
    private ProgressDialog mProgressDialog;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_share_photo);
        BaseApplication.getInstance().mActivitys.add(this);
        type = getIntent().getStringExtra("type");
        initView();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.share_photo_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        mPhotoDatas.addAll(getIntent().getStringArrayListExtra(ACTIONs.aAddData));
        gv_share_photo = (GridView) findViewById(R.id.gv_share_photo_gridView);
        mAdapter = new SharePhotoAdapter(this, mPhotoDatas);
        gv_share_photo.setAdapter(mAdapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.action_share_to:
                // 弹框并生成长图
                if (mAdapter.mSelectedShare.size() <= 0) {
                    SnackBarUtils.makeShort(mToolbar, "请先选择相片").show();
                } else {
                    mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_IMG);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap res = getResPhoto();
                            String path = saveBitmap(res);
                            mProgressDialog.dismiss();
                            SharePhoto(path);
                        }
                    }, 200);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    public void SharePhoto(String photoUri, final Activity activity) {
//        Intent shareIntent = new Intent(Intent.ACTION_SEND);
//        File file = new File(photoUri);
//        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
//        shareIntent.setType("image/jpeg");
//        startActivity(Intent.createChooser(shareIntent, activity.getTitle()));
//    }

    public void SharePhoto(String photoUri) {
        Intent intent = new Intent(SharePhotoActivity.this, StatusShareActivity.class);
        intent.putExtra("photoUri", photoUri);
        intent.putExtra("type", type);
        startActivity(intent);
    }


    public String saveBitmap(Bitmap bm) {
        File yinianfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(yinianfile.mkdir() || yinianfile.isDirectory())) {
            yinianfile.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian/" + System.currentTimeMillis() + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.toString();
    }

    private Bitmap getResPhoto() {
        int borderWidth = 6;
        int width = DisplayUtils.getScreenWidthPixels(this) / 2 + borderWidth * 2;
        int height = 0;
        Bitmap resPic = BitmapFactory.decodeResource(getResources(), R.drawable.ic_watermarke);
        Bitmap ic = mAdapter.resizeImage(resPic, width * 2 / 5, (width * 2 / 5 * resPic.getHeight() / resPic.getWidth()));
        for (int i = 0; i < mAdapter.mSelectedShare.size(); i++) {
            height += mAdapter.getBitmap(i).getHeight();
        }
        height += (mAdapter.mSelectedShare.size() + 1) * borderWidth + borderWidth / 2 + ic.getHeight();
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.WHITE);
        int martop = borderWidth;
        for (int i = 0; i < mAdapter.mSelectedShare.size(); i++) {
            canvas.drawBitmap(mAdapter.getBitmap(i), borderWidth, martop, null);
            martop += mAdapter.getBitmap(i).getHeight() + borderWidth;
        }
        canvas.drawBitmap(ic, (width - borderWidth - ic.getWidth()), height - borderWidth / 2 - ic.getHeight(), null);

        Paint p = new Paint();
        p.setColor(Color.BLACK);
        p.setAntiAlias(true);   //去除锯齿
        p.setFilterBitmap(true);//对位图进行滤波处理
        p.setTextSize(ic.getHeight() * 2 / 3);
        canvas.drawText("作者:" + application.getCurUser().getUnickname(), borderWidth, height - borderWidth, p);
        return result;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share_to, menu);
        return true;
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                mAdapter.setResource(mResource);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdapter.mSelectedShare.clear();
        mPhotoDatas.clear();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
